package xing.example.converter;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import xing.example.bean.A;

import java.lang.reflect.Field;
import java.util.Set;

/**
 * @author xing
 * @date 2023/2/15 23:55:21
 */
public class StringToAGenericConverter implements ConditionalGenericConverter {
    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        // 做一个是 StringToA 且 A 含有字段 i 的判断
        // StringToA
        boolean stringToA = sourceType.getType().equals(String.class) && targetType.getType().equals(A.class);
        // A 含有字段 i (.getDeclaredFields() 能获取到所有声明字段，.getFields() 只能获取公开的字段，。)
        Field[] fields = targetType.getType().getDeclaredFields();
        boolean i = false;
        for (Field field : fields) {
            i = i || "i".equals(field.getName());
        }
        boolean result = stringToA && i ;
        return result;
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return null;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {

        try {
            Field i = targetType.getType().getDeclaredField("i");
            // 在这里上边代码等同于 Field i = (Field)targetType.getSource();
            if(source instanceof String s) {
                i.setAccessible(true);
                // 好吧，其实只有这一句有用，但我不删。
                // return new A(Integer.parseInt((String)s) + 2);
                return new A(Integer.parseInt((String)s));
            }
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
